<template>
  <div class="alarm-management">
    <!-- 左侧站点设备树 -->
    <div class="site-tree">
      <div class="tree-header">
        <h3>站点设备</h3>
      </div>
      <div class="tree-search">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入关键字搜索"
          clearable
          @input="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="tree-content">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          node-key="id"
          :default-expanded-keys="['1', '2']"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <el-icon v-if="data.type === 'site'"><Location /></el-icon>
              <el-icon v-else><Monitor /></el-icon>
              <span>{{ node.label }}</span>
              <el-tag 
                v-if="data.type === 'device'" 
                size="small" 
                :type="getStatusType(data.status)"
              >
                {{ getStatusText(data.status) }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- 右侧告警设置 -->
    <div class="alarm-settings" v-if="currentDevice">
      <div class="settings-header">
        <h3>告警设置 - {{ currentDevice.label }}</h3>
        <el-button type="primary" @click="handleSaveSettings">保存设置</el-button>
      </div>
      <div class="settings-content">
        <el-form
          ref="settingsFormRef"
          :model="settingsForm"
          :rules="settingsRules"
          label-width="120px"
        >
          <!-- 设备算法 -->
          <el-form-item label="设备算法" prop="algorithm">
            <el-select v-model="settingsForm.algorithm" placeholder="请选择算法">
              <el-option label="人员检测" value="person_detection" />
              <el-option label="人流统计" value="crowd_counting" />
              <el-option label="异常行为" value="abnormal_behavior" />
            </el-select>
          </el-form-item>

          <!-- 人数阈值 -->
          <el-form-item label="进入人数阈值" prop="enterThreshold">
            <el-input-number 
              v-model="settingsForm.enterThreshold" 
              :min="0" 
              :max="1000"
              placeholder="请输入进入人数阈值"
            />
          </el-form-item>

          <el-form-item label="出去人数阈值" prop="exitThreshold">
            <el-input-number 
              v-model="settingsForm.exitThreshold" 
              :min="0" 
              :max="1000"
              placeholder="请输入出去人数阈值"
            />
          </el-form-item>

          <!-- 节假日设置 -->
          <el-form-item label="节假日设置">
            <el-switch
              v-model="settingsForm.skipHoliday"
              active-text="跳过法定节假日"
            />
          </el-form-item>

          <!-- 监测时段 -->
          <el-form-item label="监测时段" prop="monitorTime">
            <el-time-picker
              v-model="settingsForm.monitorTimeStart"
              placeholder="开始时间"
              format="HH:mm"
            />
            <span class="time-separator">至</span>
            <el-time-picker
              v-model="settingsForm.monitorTimeEnd"
              placeholder="结束时间"
              format="HH:mm"
            />
          </el-form-item>

          <!-- 告警通知方式 -->
          <el-form-item label="通知方式" prop="notifyMethods">
            <el-checkbox-group v-model="settingsForm.notifyMethods">
              <el-checkbox label="popup">系统弹窗</el-checkbox>
              <el-checkbox label="sms">短信通知</el-checkbox>
              <el-checkbox label="email">邮件通知</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 短信通知设置 -->
          <el-form-item 
            label="通知手机号码" 
            prop="notifyPhones"
            v-if="settingsForm.notifyMethods.includes('sms')"
          >
            <el-select
              v-model="settingsForm.notifyPhones"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入手机号码，回车确认"
            >
              <el-option
                v-for="phone in settingsForm.notifyPhones"
                :key="phone"
                :label="phone"
                :value="phone"
              />
            </el-select>
            <div class="form-tip">可输入多个手机号码，使用回车键确认</div>
          </el-form-item>

          <!-- 邮件通知设置 -->
          <el-form-item 
            label="通知邮箱地址" 
            prop="notifyEmails"
            v-if="settingsForm.notifyMethods.includes('email')"
          >
            <el-select
              v-model="settingsForm.notifyEmails"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入邮箱地址，回车确认"
            >
              <el-option
                v-for="email in settingsForm.notifyEmails"
                :key="email"
                :label="email"
                :value="email"
              />
            </el-select>
            <div class="form-tip">可输入多个邮箱地址，使用回车键确认</div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 未选择设备时的提示 -->
    <div class="no-device" v-else>
      <el-empty description="请选择需要设置的设备" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Search, Location, Monitor } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 搜索关键字
const searchKeyword = ref('')
const handleSearch = () => {
  // TODO: 实现搜索功能
  console.log('搜索关键字：', searchKeyword.value)
}

// 树形数据
const treeData = [
  {
    id: '1',
    label: '矿山一号',
    type: 'site',
    children: [
      {
        id: '1-1',
        label: '摄像头A1',
        type: 'device',
        status: 'online',
        algorithm: 'person_detection'
      },
      {
        id: '1-2',
        label: '摄像头A2',
        type: 'device',
        status: 'online',
        algorithm: 'crowd_counting'
      }
    ]
  },
  {
    id: '2',
    label: '矿山二号',
    type: 'site',
    children: [
      {
        id: '2-1',
        label: '摄像头B1',
        type: 'device',
        status: 'online',
        algorithm: 'abnormal_behavior'
      }
    ]
  }
]

const defaultProps = {
  children: 'children',
  label: 'label'
}

// 设备状态
const getStatusType = (status) => {
  const statusMap = {
    online: 'success',
    offline: 'info',
    fault: 'danger',
    disabled: 'warning'
  }
  return statusMap[status]
}

const getStatusText = (status) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    fault: '故障',
    disabled: '停用'
  }
  return statusMap[status]
}

// 当前选中的设备
const currentDevice = ref(null)

// 处理节点点击
const handleNodeClick = (data) => {
  if (data.type === 'device') {
    currentDevice.value = data
    // 加载设备的告警设置
    loadDeviceSettings(data)
  }
}

// 告警设置表单
const settingsFormRef = ref(null)
const settingsForm = reactive({
  algorithm: '',
  enterThreshold: 100,
  exitThreshold: 100,
  skipHoliday: false,
  monitorTimeStart: null,
  monitorTimeEnd: null,
  notifyMethods: ['popup'],
  notifyPhones: [],
  notifyEmails: []
})

// 表单验证规则
const settingsRules = {
  algorithm: [
    { required: true, message: '请选择设备算法', trigger: 'change' }
  ],
  enterThreshold: [
    { required: true, message: '请输入进入人数阈值', trigger: 'blur' }
  ],
  exitThreshold: [
    { required: true, message: '请输入出去人数阈值', trigger: 'blur' }
  ],
  notifyPhones: [
    { 
      type: 'array',
      validator: (rule, value, callback) => {
        if (settingsForm.notifyMethods.includes('sms') && value.length === 0) {
          callback(new Error('请至少输入一个通知手机号码'))
        } else {
          const phoneRegex = /^1[3-9]\d{9}$/
          const invalidPhone = value.find(phone => !phoneRegex.test(phone))
          if (invalidPhone) {
            callback(new Error(`手机号码 ${invalidPhone} 格式不正确`))
          } else {
            callback()
          }
        }
      },
      trigger: 'change'
    }
  ],
  notifyEmails: [
    {
      type: 'array',
      validator: (rule, value, callback) => {
        if (settingsForm.notifyMethods.includes('email') && value.length === 0) {
          callback(new Error('请至少输入一个通知邮箱地址'))
        } else {
          const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
          const invalidEmail = value.find(email => !emailRegex.test(email))
          if (invalidEmail) {
            callback(new Error(`邮箱地址 ${invalidEmail} 格式不正确`))
          } else {
            callback()
          }
        }
      },
      trigger: 'change'
    }
  ]
}

// 加载设备告警设置
const loadDeviceSettings = (device) => {
  // TODO: 调用接口加载设备的告警设置
  // 这里模拟加载数据
  settingsForm.algorithm = device.algorithm
  settingsForm.enterThreshold = 100
  settingsForm.exitThreshold = 100
  settingsForm.skipHoliday = false
  settingsForm.monitorTimeStart = new Date(2024, 0, 1, 9, 0)
  settingsForm.monitorTimeEnd = new Date(2024, 0, 1, 18, 0)
  settingsForm.notifyMethods = ['popup']
  settingsForm.notifyPhones = []
  settingsForm.notifyEmails = []
}

// 保存设置
const handleSaveSettings = async () => {
  if (!settingsFormRef.value) return
  
  try {
    await settingsFormRef.value.validate()
    // TODO: 调用接口保存设置
    console.log('保存设置：', settingsForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('表单验证失败：', error)
  }
}
</script>

<style scoped>
.alarm-management {
  height: 100%;
  display: flex;
  gap: 16px;
}

/* 左侧树形结构样式 */
.site-tree {
  width: 300px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.tree-header {
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.tree-header h3 {
  margin: 0;
  font-size: 16px;
}

.tree-search {
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.tree-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

/* 右侧设置区域样式 */
.alarm-settings {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
  min-width: 0;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.settings-header h3 {
  margin: 0;
  font-size: 16px;
}

.settings-content {
  max-width: 800px;
}

.time-separator {
  margin: 0 12px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 未选择设备时的提示 */
.no-device {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 4px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}
</style>